import { ElLoading, LoadingOptions } from 'element-plus'
import { LoadingInstance } from 'element-plus/es/components/loading/src/loading'

const defaultOptions: LoadingOptions = {
	text: '加载中...',
	lock: true,
	background: 'rgba(0, 0, 0, 0.7)',
}

const fetchWithLoading = (fnc: Function, options: LoadingOptions = {}) => {
	let loadingInstance: LoadingInstance,
		_options = { ...options, ...defaultOptions }
	const showLoading = (options: LoadingOptions) => {
			loadingInstance = ElLoading.service(options)
		},
		hideLoading = () => {
			if (loadingInstance) loadingInstance.close()
		}

	return (...args: any) => {
		try {
			showLoading(_options)
			const result = fnc(...args)
			const isPromise = result instanceof Promise
			if (!isPromise) {
				hideLoading()
				return result
			}
			return result
				.then(res => res)
				.catch(err => {
					throw err
				})
				.finally(() => hideLoading())
		} catch (error) {
			hideLoading()
			throw error
		}
	}
}

export default fetchWithLoading
